package com.hw.servlet;

import com.google.gson.Gson;
import com.hw.dao.BookRDao;
import com.hw.entity.Bookread;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Type;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "RBServlet",urlPatterns = "/admin/rb")
public class RBServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;utf-8");
        request.setCharacterEncoding("utf-8");
        HttpSession session=request.getSession();
        String account= (String) session.getAttribute("account");
        BookRDao bookRDao=new BookRDao();
        List<Bookread> lb=bookRDao.fromSelct(account);
        Gson gson=new Gson();
        Map<String ,Object> map=new HashMap<>();
        map.put("user",account);
        map.put("data",lb);
        PrintWriter out=response.getWriter();
        out.print(gson.toJson(map));
        String mission=request.getParameter("mission");
        String datas=request.getParameter("datas");
        if (datas !=null){
            Bookread bookread = gson.fromJson(datas,Bookread.class);
            if (mission.equals("insert")){
            bookread.setAccount(account);
            System.out.println(bookread);
            addBookRead(bookread);

        }else if (mission.equals("delete")){
                bookread.setAccount(account);
                System.out.println(bookread);
                deleteBookRead(bookread);
            }
        }



    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
    private  void addBookRead(Bookread bookread){
        BookRDao bookRDao=new BookRDao();
        bookRDao.insert(bookread);
    }
    private void deleteBookRead(Bookread bookread){
        BookRDao bookRDao=new BookRDao();
        bookRDao.deletd(bookread.getAccount(),bookread.getBookName());
    }

}
